<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="配件编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入配件编号" v-decorator="['materialCode', validatorRules.materialCode]" :disabled="disableEdit" />
        </a-form-item>
        <a-form-item label="配件名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入配件名称" v-decorator="['materialName', validatorRules.materialName]" />
        </a-form-item>
        <a-form-item label="物料图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-image-upload v-decorator="['materialImage']" :number="1" :bizPath="bizPath" :returnUrl="true" @change="handleImageChange" @error="handleImageError"></j-image-upload>
        </a-form-item>
        <a-form-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入规格型号" v-decorator="['specification']" />
        </a-form-item>
        <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入单位" v-decorator="['unit', validatorRules.unit]" />
        </a-form-item>
        <a-form-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入品牌" v-decorator="['brand']" />
        </a-form-item>
        <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入颜色" v-decorator="['color']" />
        </a-form-item>
        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="4" />
        </a-form-item>
        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="radio" v-decorator="['status', {initialValue: '0'}]" :triggerChange="true" dictCode="wms_material_status" />
        </a-form-item>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { materialAdd, materialEdit } from '@/api/wms'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import { getAction } from '@/api/manage'
  import JModal from '@/components/jeecg/JModal/JModal'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import pick from 'lodash.pick'
  import moment from 'moment'

  export default {
    name: 'FittingModal',
    components: {
      JDictSelectTag,
      JModal,
      JImageUpload
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          materialCode: { rules: [{ required: true, message: '请输入配件编号!' }] },
          materialName: { rules: [{ required: true, message: '请输入配件名称!' }] },
          unit: { rules: [{ required: true, message: '请输入单位!' }] },
        },
        bizPath: 'material/fitting',
        disableEdit: false,
        url: {
          add: '/wms/material/add',
          edit: '/wms/material/edit'
        }
      }
    },
    methods: {
      add() {
        this.edit({
          materialType: '2', // 配件类型
          status: '0' // 默认启用状态
        })
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.disableEdit = !!this.model.id
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'materialCode', 'materialName', 'materialType', 'specification', 'unit', 'brand', 'color', 'materialImage', 'remark', 'status'))
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            
            // 处理图片路径
            if (values.materialImage && values.materialCode) {
              // 确保materialImage是字符串
              if (typeof values.materialImage !== 'string') {
                console.warn('物料图片不是字符串类型:', values.materialImage);
                if (values.materialImage && typeof values.materialImage === 'object') {
                  if (values.materialImage.response && values.materialImage.response.message) {
                    values.materialImage = values.materialImage.response.message;
                  } else {
                    values.materialImage = JSON.stringify(values.materialImage);
                  }
                } else {
                  values.materialImage = '';
                }
              }
              
              // 重命名图片，格式：租户ID_物料编码
              const tenantId = this.$store.getters.userInfo.tenantId || '';
              values.materialImage = values.materialImage.replace(/\/material\/fitting\//, `/material/fitting/${tenantId}_${values.materialCode}_`);
            }
            
            let formData = Object.assign(this.model, values)
            
            let obj = {
              ...formData
            }
            
            if (!this.model.id) {
              // 新增
              materialAdd(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            } else {
              // 编辑
              materialEdit(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            }
          }
        })
      },
      handleCancel() {
        this.close()
      },
      handleImageChange(value) {
        console.log('物料图片变更:', value);
        
        // 处理不同类型的输入
        let imagePath = '';
        
        if (typeof value === 'string') {
          // 如果是字符串，直接使用
          imagePath = value;
        } else if (value && typeof value === 'object') {
          // 如果是对象，尝试提取路径
          if (value.response && value.response.message) {
            imagePath = value.response.message;
          } else if (Array.isArray(value)) {
            // 如果是数组，提取每个元素的路径并拼接
            imagePath = value.map(item => {
              if (typeof item === 'string') return item;
              if (item && item.response && item.response.message) return item.response.message;
              return '';
            }).filter(Boolean).join(',');
          } else {
            console.warn('物料图片格式不正确:', JSON.stringify(value));
          }
        }
        
        console.log('处理后的物料图片路径:', imagePath);
        
        // 设置表单值
        this.form.setFieldsValue({
          materialImage: imagePath
        });
      },
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        // 替换为默认的无图片图标
        e.target.style.display = 'none';
        const container = e.target.parentNode;
        if (container) {
          // 添加一个图标表示图片加载失败
          const icon = document.createElement('i');
          icon.className = 'anticon anticon-picture';
          icon.style.fontSize = '24px';
          icon.style.color = '#d9d9d9';
          container.insertBefore(icon, e.target);

          // 添加错误提示文本
          const errorText = document.createElement('div');
          errorText.innerText = '图片不存在';
          errorText.style.color = '#ff4d4f';
          errorText.style.fontSize = '12px';
          errorText.style.marginTop = '4px';
          container.appendChild(errorText);
        }
      }
    }
  }
</script> 